<template>
  <div v-if="assignmentData" class="assignment-view">
    <el-card>
      <template #header>
        <div class="card-header">
          <h1>{{ assignmentData.title }}</h1>
          <p>截止日期: {{ new Date(assignmentData.deadline).toLocaleString() }}</p>
        </div>
      </template>

      <div
        v-for="(question, index) in assignmentData.questions"
        :key="question.questionId"
        class="question-item"
      >
        <p class="markdown-content" v-html="renderMarkdown(`${index + 1}. ${question.content}`)" />

        <template v-if="question.type === 'SINGLE_CHOICE'">
          <el-radio-group v-model="answers[question.questionId]">
            <el-radio
              v-for="(option, key) in safeParseOptions(question.options)"
              :key="key"
              :label="key"
            >
              <span v-html="renderMarkdown(`${key}. ${option}`)"></span>
            </el-radio>
          </el-radio-group>
        </template>

        <template v-else-if="question.type === 'MULTIPLE_CHOICE'">
          <el-checkbox-group v-model="multiAnswers[question.questionId]">
            <el-checkbox
              v-for="(option, key) in safeParseOptions(question.options)"
              :key="key"
              :label="key"
            >
              <span v-html="renderMarkdown(`${key}. ${option}`)"></span>
            </el-checkbox>
          </el-checkbox-group>
        </template>

        <template v-else-if="['SUBJECTIVE', 'FILL_IN_BLANK'].includes(question.type)">
          <el-upload
            :auto-upload="true"
            :file-list="uploadFileList[question.questionId]"
            :http-request="(option) => handleCustomUpload(option, question.questionId)"
            :limit="5"
            :on-preview="(file) => handlePreview(file)"
            :on-remove="(file) => handleRemove(question.questionId, file)"
            accept="image/*"
            class="upload-demo"
            list-type="picture-card"
            multiple
          >
            <el-icon>
              <Plus />
            </el-icon>
          </el-upload>
        </template>
      </div>

      <div class="submit-button-container">
        <el-button :loading="submitLoading" size="large" type="primary" @click="submitHomework">
          提交作业
        </el-button>
      </div>
    </el-card>
  </div>

  <div v-else v-loading="loading" style="height: 80vh"></div>

  <el-dialog v-model="previewVisible" :show-close="true" width="60%">
    <img :src="previewImage" alt="预览图片" style="width: 100%" />
  </el-dialog>
</template>
<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { apiClient, uploadClient } from '@/api'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { renderMarkdown } from '@/api/utils.ts'

const route = useRoute()
const router = useRouter()
const assignmentId = Number(route.params.id)

const assignmentData = ref<any>(null)
const loading = ref(true)
const submitLoading = ref(false)
const answers = reactive<Record<number, string>>({})
const uploadFileList = reactive<Record<number, any[]>>({})

const previewVisible = ref(false)
const previewImage = ref('')

const handlePreview = (file: any) => {
  previewImage.value = file.url || file.response?.url || ''
  previewVisible.value = true
}

const multiAnswers = reactive<Record<number, string[]>>({})

const fetchAssignmentDetails = async () => {
  loading.value = true
  try {
    const response = await apiClient.get(`/assignments/${assignmentId}`)
    const data = response.data
    if (data && data.questions) {
      data.questions.forEach((q: any) => {
        try {
          q.parsedOptions = q.options ? JSON.parse(q.options) : {}
        } catch (e) {
          console.error('解析题目选项失败', e, q.options)
          q.parsedOptions = {}
        }
      })
    }
    assignmentData.value = data
  } catch (error) {
    ElMessage.error('加载作业失败')
  } finally {
    loading.value = false
  }
}


const safeParseOptions = (optionsStr: string): Record<string, string> => {
  try {
    const parsed = JSON.parse(optionsStr)
    return parsed && typeof parsed === 'object' ? parsed : {}
  } catch {
    return {}
  }
}

const handleCustomUpload = async (option: any, questionId: number) => {
  const file = option.file
  const formData = new FormData()
  formData.append('file', file)

  try {
    const res = await uploadClient.post('/user/image', formData)
    const url = res.data?.url
    if (!url) throw new Error('无效的返回结果')
    if (!uploadFileList[questionId]) uploadFileList[questionId] = []
    uploadFileList[questionId].push({ name: file.name, url })
    answers[questionId] = JSON.stringify(
      uploadFileList[questionId].map((f) => ({ image: f.url }))
    )
    ElMessage.success('上传成功')
  } catch (err) {
    console.error('上传失败', err)
    ElMessage.error('上传失败')
  }
}


const handleRemove = (questionId: number, file: any) => {
  if (!uploadFileList[questionId]) return
  uploadFileList[questionId] = uploadFileList[questionId].filter((f) => f.url !== file.url)
  if (uploadFileList[questionId].length === 0) {
    delete answers[questionId]
  } else {
    answers[questionId] = JSON.stringify(uploadFileList[questionId].map((f) => ({ image: f.url })))
  }
}

const submitHomework = () => {
  ElMessageBox.confirm('确认要提交作业吗？提交后将无法修改。', '提示', {
    confirmButtonText: '确认提交',
    cancelButtonText: '再检查一下',
    type: 'warning',
  }).then(async () => {
    submitLoading.value = true
    try {
      const questions = assignmentData.value.questions
      assignmentData.value.questions.forEach((q: any) => {
        if (q.type === 'MULTIPLE_CHOICE') {
          const selected = multiAnswers[q.questionId]
          if (selected && selected.length > 0) {
            answers[q.questionId] = JSON.stringify(selected)
          }
        }
      })
      const submission = {
        answers: questions.map((q: any) => {
          const raw = answers[q.questionId]
          return {
            questionId: q.questionId,
            userAnswer: raw ?? '',
          }
        }),
      }

      const incomplete = submission.answers.some((a) => {
        if (!a.userAnswer) return true
      })

      if (incomplete) {
        ElMessage.warning('请完成所有题目后再提交！')
        submitLoading.value = false
        return
      }

      await apiClient.post(`/assignments/${assignmentId}/submit`, submission)
      ElMessage.success('作业提交成功！')
      router.push('/dashboard')
    } catch (error) {
      ElMessage.error('提交失败，可能已过截止日期或已提交过。')
    } finally {
      submitLoading.value = false
    }
  })
}

onMounted(fetchAssignmentDetails)
</script>

<style scoped>
.assignment-view {
  padding: 20px;
}

.card-header h1 {
  margin: 0;
}

.card-header p {
  margin: 5px 0 0;
  color: #909399;
}

.question-item {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #f0f2f5;
}

.markdown-content {
  font-size: 15px;
  line-height: 1.6;
  word-break: break-word;
}

.el-radio-group {
  display: block;
}

.el-radio {
  margin: 10px 0;
}

.submit-button-container {
  text-align: center;
  margin-top: 30px;
}

.upload-container {
  margin-top: 10px;
}
</style>
